import * as SparkMD5 from "spark-md5";
import {FileInfo, FileType} from "@shared/models/FileInfo";
import {fileTypeImgUrl} from "@shared/models/DiskPageModel";
import {HttpHeaders} from "@angular/common/http";
import {Result} from "@shared/models/Result";
import {Observable} from "rxjs";
import {StatusCode} from "@shared/models/StatusCode";

export class BBYUtils {
  public static videoSuffix=/mp4|mov|m4v|m4a|avi/
  public static imgSuffix=/jpeg|gif|png|svg|jpg|webp/
  public static clone(obj: any) {
    return JSON.parse(JSON.stringify(obj))
  }
  public static userIdNameMap = new Map()
  MimetypesKind = {
    opus: 'video/ogg',
    ogv: 'video/ogg',
    mp4: 'video/mp4',
    mov: 'video/mp4',
    m4v: 'video/mp4',
    mkv: 'video/x-matroska',
    m4a: 'audio/mp4',
    mp3: 'audio/mpeg',
    aac: 'audio/aac',
    caf: 'audio/x-caf',
    flac: 'audio/flac',
    oga: 'audio/ogg',
    wav: 'audio/wav',
    m3u8: 'application/x-mpegURL',
    jpg: 'image/jpeg',
    jpeg: 'image/jpeg',
    gif: 'image/gif',
    png: 'image/png',
    svg: 'image/svg+xml',
    webp: 'image/webp'
  }
  /**
   * Generate file hash
   * @param file
   * @param callback 回调函数
   */
  public static md5File(file: File, callback: (md5: string) => void) {
    const blobSlice = File.prototype.slice;
    let chunkSize = 2097152,                             // Read in chunks of 2MB
      chunks = Math.ceil(file.size / chunkSize),
      currentChunk = 0,
      spark = new SparkMD5.ArrayBuffer(),
      fileReader = new FileReader();
    fileReader.onload = function (e) {
      // @ts-ignore
      spark.append(e.target.result);                   // Append array buffer
      currentChunk++;
      if (currentChunk < chunks) {
        loadNext();
      } else {
        const hash = spark.end();
        callback(hash)
      }
    };
    fileReader.onerror = function () {
      console.warn('oops, something went wrong.');
    };

    function loadNext() {
      var start = currentChunk * chunkSize,
        end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
      fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
    }

    loadNext();
  }

  public static guid() {
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

  public static getFileSuffix(name: string) {
    let i = name.lastIndexOf('.');
    if (i == -1) {
      return 'dir';
    }
    return name.substring(i + 1);
  }
  public static getFileType(file:FileInfo) {
    if (!file.isFile){
      return FileType.DIR;
    }
   let suffix = BBYUtils.getFileSuffix(file.name)
    if (suffix.match(BBYUtils.videoSuffix)){
      return FileType.VIDEO
    }else if (suffix.match(this.imgSuffix)){
      return FileType.IMG
    }else if (suffix.match(/txt|md|doc|docx|pdf/)){
      return FileType.TEXT
    }else  if (suffix.match(/zip|rar|tar/)){
      return FileType.ZIP
    }
    return FileType.UNKNOWN
  }

  static getTypeImg(file: FileInfo) {
    let url = fileTypeImgUrl[file.type]
    return url? url:'assets/img/unknown.png'
  }

  static getIdFromPath(path: string) {
    let i = path.indexOf('/')||path.indexOf('\\');
    return i? path.substring(0,i):path;
  }

  static getIdFromURI(path: string, offset: number) {

  }

  static createHeadersOption(pass?:string) {
    let token = localStorage.getItem('token')
    console.log(token)
    if (pass){
      console.log('pass',pass)
      let headers = new HttpHeaders().set("filePw",pass);
      if (token) headers.set("token", token)
      return {headers:headers}
    }else {
      return token ? {headers: new HttpHeaders().set("token", token)} : {}
    }
  }

  static handelResult(observable: Observable<Result>, success: (res: Result) => void, fail: (res: Result) => void) {
    observable.subscribe(res=>{
      if (res.code==StatusCode.OK){
        success(res)
      }else if (res.code==StatusCode.NOT_LOGIN){
        if (!window.location.href.endsWith('/login')) {
          // window.location.href='/user/login'
          let ask = window.confirm('您目前还未登录，是否去登录？')
          if (ask){
            window.location.href='/user/login'
          }
        }
        console.log(window.location.href)
      }else {
        fail(res)
      }
    },error => {
      fail({code:error.status,msg:'网络连接失败'})
    })
  }

  static ObjToUrlParam(url:string, data: any) {
    let str=''
    for (let dataKey in data) {
      str = `${str}&${dataKey}=${data[dataKey]}`
    }
    return url+'?'+encodeURI(str.substring(1))
  }

  static getPermissionDetail(file: FileInfo) {
    let token = localStorage.getItem('token');
    return token? file.permission?.user:file.permission?.ann
  }

}
